//
//  MapViewRoutePlan.m
//  YueYueSpecailCarDriver
//
//  Created by 李亚军 on 17/2/27.
//  Copyright © 2017年 黄旺鑫. All rights reserved.
//

#import "MapViewRoutePlan.h"
#import "MANaviRoute.h"
#import "CommonUtility.h"
#import <AMapSearchKit/AMapSearchKit.h>
#import "ErrorInfoUtility.h"
#import "HeaderMacro.h"
#import <QXDriverConfiguration/QXDriverConfiguration.h>
#import <MAMapKit/MAMapKit.h>
#import "LocationManager.h"
#import "UserLocationModel.h"
#import "MAAnnotationView+Category.h"
#import <AMapFoundationKit/AMapFoundationKit.h>
#import "CarImageManager.h"

static const NSString *RoutePlaningViewControllerStartTitle = @"起点";
static const NSString *RoutePlanningViewControllerDestinationTitle = @"终点";


@interface MapViewRoutePlan () <MAMapViewDelegate , AMapSearchDelegate>



/**
 起始点经纬度
 */
@property(nonatomic , assign) CLLocationCoordinate2D startCoordinate;
/**
 终点经纬度
 */
@property(nonatomic , assign) CLLocationCoordinate2D destnationCoordinate;

/**
 路径规划类型
 */
@property(nonatomic , strong) AMapSearchAPI *search;

@property(nonatomic , strong) AMapRoute *route;


/**
 当前路线方案索引值
 */
@property(nonatomic , assign) NSInteger currentCourse;

/**
 路线方案个数
 */
@property(nonatomic , assign) NSInteger totalCourse;





/**
 用于显示当前路面方案
 */
@property(nonatomic , strong) MANaviRoute *naviRoute;



@property(nonatomic , strong) MAAnnotationView *driverLocation;

@end

@implementation MapViewRoutePlan

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initMapView];
    [self initAMapSearchAPI];

}


- (void)initMapView {
    
    self.mapView = [[MAMapView alloc] init];
    self.mapView.delegate = self;
    self.mapView.showsUserLocation = YES;
    self.mapView.userTrackingMode = MAUserTrackingModeFollow;
    
    [self.view addSubview:self.mapView];
    
    self.startAnnotation = [[MAPointAnnotation alloc] init];
    self.destinationAnnotation = [[MAPointAnnotation alloc] init];
    
//    self.mapView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    
//    self.mapView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin;
//    self.mapView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    self.mapView.translatesAutoresizingMaskIntoConstraints = NO; // 为NO下面的约束生效
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.mapView attribute:(NSLayoutAttributeTop) relatedBy:(NSLayoutRelationEqual) toItem:self.view attribute:(NSLayoutAttributeTop) multiplier:1 constant:0]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.mapView attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeLeft multiplier:1 constant:0]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.mapView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeBottom multiplier:1 constant:0]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.mapView attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeRight multiplier:1 constant:0]];
}

- (void)initAMapSearchAPI {

    self.search = [[AMapSearchAPI alloc] init];
    self.search.delegate = self;
}



/**
 展示当前的路线
 */
- (void)presentCurrentCource {
    
    MANaviAnnotationType type = MANaviAnnotationTypeDrive;
    
    // 当前需要展示的路线
    self.naviRoute = [MANaviRoute naviRouteForPath:self.route.paths[self.currentCourse] withNaviType:type showTraffic:NO startPoint:[AMapGeoPoint locationWithLatitude:self.startCoordinate.latitude longitude:self.startCoordinate.longitude] endPoint:[AMapGeoPoint locationWithLatitude:self.destnationCoordinate.latitude longitude:self.destnationCoordinate.longitude]];
    
    
    self.naviRoute.routeColor = Color_3585ff; // 路线颜色
    
    
    [self.naviRoute addToMapView:self.mapView]; // 将路线添加到地图

    self.mapView.showsUserLocation = YES;
    self.mapView.userTrackingMode = MAUserTrackingModeFollow;
    self.mapView.showTraffic = YES;
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        [self.mapView setVisibleMapRect:[CommonUtility mapRectForOverlays:self.naviRoute.routePolylines] edgePadding:self.mapRoutePlanEdgeInsets animated:NO];
    });
    
    
    [[NSNotificationCenter defaultCenter] postNotificationName:NotificaitonName_RoutePlanningSuccess object:nil];
}

/* 清空地图上已有的路线. */
- (void)clear
{
    dispatch_async(dispatch_get_main_queue(), ^{
        
        [self.naviRoute removeFromMapView];
        [self.mapView removeAnnotation:self.startAnnotation];
        [self.mapView removeAnnotation:self.destinationAnnotation];
    });
    
}

#pragma mark - MAMapViewDelegate

- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id<MAOverlay>)overlay
{
    if ([overlay isKindOfClass:[LineDashPolyline class]])
    {
        MAPolylineRenderer *polylineRenderer = [[MAPolylineRenderer alloc] initWithPolyline:((LineDashPolyline *)overlay).polyline];
        polylineRenderer.lineWidth   = 8;
        polylineRenderer.lineDash = YES;
        polylineRenderer.lineCapType = kMALineCapRound;
        polylineRenderer.lineJoinType = kMALineJoinRound;
        polylineRenderer.strokeColor = [UIColor redColor];
        
        return polylineRenderer;
    }
    if ([overlay isKindOfClass:[MANaviPolyline class]])
    {
        MANaviPolyline *naviPolyline = (MANaviPolyline *)overlay;
        MAPolylineRenderer *polylineRenderer = [[MAPolylineRenderer alloc] initWithPolyline:naviPolyline.polyline];
        
        polylineRenderer.lineWidth = 8;
        polylineRenderer.lineCapType = kMALineCapRound;
        polylineRenderer.lineJoinType = kMALineJoinRound;
        if (naviPolyline.type == MANaviAnnotationTypeWalking)
        {
            polylineRenderer.strokeColor = self.naviRoute.walkingColor;
        }
        else if (naviPolyline.type == MANaviAnnotationTypeRailway)
        {
            polylineRenderer.strokeColor = self.naviRoute.railwayColor;
        }
        else
        {
            polylineRenderer.strokeColor = self.naviRoute.routeColor;
        }
        
        return polylineRenderer;
    }
    if ([overlay isKindOfClass:[MAMultiPolyline class]])
    {
        MAMultiColoredPolylineRenderer * polylineRenderer = [[MAMultiColoredPolylineRenderer alloc] initWithMultiPolyline:overlay];
        
        polylineRenderer.lineWidth = 10;
        polylineRenderer.strokeColors = [self.naviRoute.multiPolylineColors copy];
        polylineRenderer.gradient = YES;
        polylineRenderer.lineCapType = kMALineCapRound;
        polylineRenderer.lineJoinType = kMALineJoinRound;
        return polylineRenderer;
    }
    
    return nil;
}

- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation updatingLocation:(BOOL)updatingLocation {
    
    // 控制车头方向
    [self.driverLocation rotateWithHeading:userLocation.heading];
    
}



- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation
{
    
    if ([annotation isKindOfClass:[MAUserLocation class]])
    {
        
        self.driverLocation = [mapView dequeueReusableAnnotationViewWithIdentifier:@"UserDriverLocation"];
        
        if (self.driverLocation == nil) {
            
            self.driverLocation = [[MAAnnotationView alloc] initWithAnnotation:annotation
                                                             reuseIdentifier:@"UserDriverLocation"];
        }
        
        if (self.isShowUser) {
            
//            self.driverLocation.image = [QXDriverConfiguration imageWithName:@"car"];
//            self.driverLocation.image = [CarImageManager getCarImage];
            self.driverLocation.image = [UIImage imageNamed:@"map_icon_car copy"];
        }else {
            
            self.driverLocation.image = [UIImage imageNamed:@""];
        }
        
        
        return self.driverLocation;
    }
    
    
    if ([annotation isKindOfClass:[MAPointAnnotation class]])
    {
        static NSString *routePlanningCellIdentifier = @"RoutePlanningCellIdentifier";
        
        MAAnnotationView *poiAnnotationView = (MAAnnotationView*)[self.mapView dequeueReusableAnnotationViewWithIdentifier:routePlanningCellIdentifier];
        if (poiAnnotationView == nil)
        {
            poiAnnotationView = [[MAAnnotationView alloc] initWithAnnotation:annotation
                                                             reuseIdentifier:routePlanningCellIdentifier];
        }
        
        poiAnnotationView.canShowCallout = YES;
        
        
        
        if ([annotation isKindOfClass:[MANaviAnnotation class]])
        {
            switch (((MANaviAnnotation*)annotation).type)
            {
                case MANaviAnnotationTypeRailway:
                    poiAnnotationView.image = [UIImage imageNamed:@"railway_station"];
                    break;
                    
                case MANaviAnnotationTypeBus:
                    poiAnnotationView.image = [UIImage imageNamed:@"bus"];
                    break;
                    
                case MANaviAnnotationTypeDrive:
                    
                    if ([poiAnnotationView.annotation.title isEqualToString:@"起点"]) {
                        
                        if (self.orderStatusEnumCode == OrderStatusEnumCode_DriverReceivedOrder_DetermineStroke) {
                        
//                            poiAnnotationView.image = [QXDriverConfiguration imageWithName:@"public_pic_qidian"];
                            poiAnnotationView.image = [QXDriverConfiguration imageWithName:@"public_pic_qidian"];
                        }else if (self.orderStatusEnumCode == OrderStatusEnumCode_DriverArrived_WaitingForPassengers) {
                            
                            poiAnnotationView.image = [QXDriverConfiguration imageWithName:@""];
                        }else {
                            
                            poiAnnotationView.image = [QXDriverConfiguration imageWithName:@"car"];
                        }
                        
                    }else if ([poiAnnotationView.annotation.title isEqualToString:@"终点"]) {
                        
                        if (self.orderStatusEnumCode == OrderStatusEnumCode_DriverSetOut_GoToPickUpPassengers) {
                            
                            poiAnnotationView.image = [QXDriverConfiguration imageWithName:@"public_pic_qidian"];
                        }else if (self.orderStatusEnumCode == OrderStatusEnumCode_DriverArrived_WaitingForPassengers) {
                            
                            poiAnnotationView.image = [QXDriverConfiguration imageWithName:@""];
                        }else if (self.orderStatusEnumCode == OrderStatusEnumCode_PickedUpPasengers_StrokeStart) {
                            
                            poiAnnotationView.image = [QXDriverConfiguration imageWithName:@"public_pic_zhongdian"];
                        }
                        
                    }else {
                    
                        poiAnnotationView.image = [UIImage imageNamed:@""];
                    }
                    
                    break;
                    
                case MANaviAnnotationTypeWalking:
                    poiAnnotationView.image = [UIImage imageNamed:@"man"];
                    break;
                    
                default:
                    break;
            }
        }
        else
        {
            /* 起点. */
            if ([[annotation title] isEqualToString:(NSString*)RoutePlaningViewControllerStartTitle])
            {
//                poiAnnotationView.image = [UIImage imageNamed:@"startPoint"];
//                poiAnnotationView.image = [QXDriverConfiguration imageWithName:@"car"];
//                poiAnnotationView.image = [QXDriverConfiguration imageWithName:@"public_pic_qidian"];
                
                if (self.orderStatusEnumCode ==  OrderStatusEnumCode_PassengerOrder_WaitingForAnswer ||
                    self.orderStatusEnumCode == OrderStatusEnumCode_DriverReceivedOrder_DetermineStroke ||
                    self.orderStatusEnumCode == OrderStatusEnumCode_NewStroke_PassengerCancel ||
                    self.orderStatusEnumCode == OrderStatusEnumCode_PassengersCancel_StrokeDetemination_DriverNotArrive ||
                    self.orderStatusEnumCode == OrderStatusEnumCode_PassengersCancel_StrokeDetemination_DriverArrived ||
                    self.orderStatusEnumCode == OrderStatusEnumCode_NewStroke_DriverCancel ||
                    self.orderStatusEnumCode == OrderStatusEnumCode_NoFare_StrokeDetermination_PassengersCancelOrder ||
                    self.orderStatusEnumCode == OrderStatusEnumCode_NoFare_GotoPickUpPassengers_PassengersCancelOrder ||
                    self.orderStatusEnumCode == OOrderStatusEnumCode_NoFare_WaitingForPassengers_PassengersCancelOrder ||
                    self.orderStatusEnumCode == OrderStatusEnumCode_HaveFare_StrokeDetermination_PassengersCancelOrder ||
                    self.orderStatusEnumCode == OrderStatusEnumCode_HaveFare_GotoPickUpPassengers_PassengersCancelOrder ||
                    self.orderStatusEnumCode == OrderStatusEnumCode_HaveFare_WaitingForPassengers_PassengersCancelOrder ||
                    self.orderStatusEnumCode == OrderStatusEnumCode_NoFare_StrokeDetermination_DriverCancelOrder ||
                    self.orderStatusEnumCode == OrderStatusEnumCode_NoFare_GotoPickUpPassengers_DriverCancelOrder ||
                    self.orderStatusEnumCode == OrderStatusEnumCode_HaveFare_StrokeDetermination_DriverCancelOrder ||
                    self.orderStatusEnumCode == OrderStatusEnumCode_HaveFare_GotoPickUpPassengers_DriverCancelOrder ||
                    self.orderStatusEnumCode == OrderStatusEnumCode_HaveFare_WaitingForPassengers_DriverCancelOrder ||
                    self.orderStatusEnumCode == OrderStatusEnumCode_OrderClosedByCustomerService) {
                    
                    poiAnnotationView.image = [QXDriverConfiguration imageWithName:@"public_pic_qidian"];
                }else {
                    
                    if (self.isShowUser == NO) {
                        
                        poiAnnotationView.image = [QXDriverConfiguration imageWithName:@"public_pic_qidian"];
                    }else {
                        poiAnnotationView.image = [QXDriverConfiguration imageWithName:@""];
                    }
                }
            }
            /* 终点. */
            else if([[annotation title] isEqualToString:(NSString*)RoutePlanningViewControllerDestinationTitle])
            {
//                poiAnnotationView.image = [UIImage imageNamed:@"endPoint"];
//                poiAnnotationView.image = [QXDriverConfiguration imageWithName:@"public_pic_zhongdian"];
//                if (self.orderState == OrderState_GoToPickUpPassenger) {
//                    
//                    //                            poiAnnotationView.image = [QXDriverConfiguration imageWithName:@"public_pic_zhongdian"];
//                    poiAnnotationView.image = [QXDriverConfiguration imageWithName:@"public_pic_qidian"];
//                }else if (self.orderState == OrderState_GoToDestination) {
//                    
//                    poiAnnotationView.image = [QXDriverConfiguration imageWithName:@"public_pic_zhongdian"];
//                }
                
                if (self.orderStatusEnumCode == OrderStatusEnumCode_DriverSetOut_GoToPickUpPassengers) {
                    
                    poiAnnotationView.image = [QXDriverConfiguration imageWithName:@"public_pic_qidian"];
                }else {
                    
                    poiAnnotationView.image = [QXDriverConfiguration imageWithName:@"public_pic_zhongdian"];
                }
                
            }
            
        }
        
        return poiAnnotationView;
    }
    
    return nil;
}

#pragma mark - AMapSearchDelegate
- (void)AMapSearchRequest:(id)request didFailWithError:(NSError *)error
{
    
}

/* 路径规划搜索回调. */
- (void)onRouteSearchDone:(AMapRouteSearchBaseRequest *)request response:(AMapRouteSearchResponse *)response
{
    if (response.route == nil)
    {
        return;
    }
    
    self.route = response.route;

    AMapPath *nowRoute = self.route.paths.firstObject;

    
    // 发送路线信息通知
    [[NSNotificationCenter defaultCenter] postNotificationName:NotificationName_RoutePlaningSuccess object:nowRoute];
    

    self.currentCourse = 0;

    
    if (response.count > 0)
    {
        [self presentCurrentCource];
    }
}

#pragma mark - 重写
- (void)setMapRoutePlanEdgeInsets:(UIEdgeInsets)mapRoutePlanEdgeInsets {

    _mapRoutePlanEdgeInsets = mapRoutePlanEdgeInsets;
    if (self.naviRoute.routePolylines > 0) {
        
        [self.mapView setVisibleMapRect:[CommonUtility mapRectForOverlays:self.naviRoute.routePolylines] edgePadding:mapRoutePlanEdgeInsets animated:YES];
    }
    
}

#pragma mark - 重新规划路线
/**
 重新绘制路线
 
 @param startPoint 起始位置
 @param destinationPoint 终点位置
 @param wayPoints 途径点
 */
- (void)reDrawRouteLineWithStartPoint:(AMapGeoPoint *)startPoint destinationPoint:(AMapGeoPoint *)destinationPoint wayPoints:(NSArray <AMapGeoPoint *>*)wayPoints {
    
    [self clear];
    
    self.startCoordinate = CLLocationCoordinate2DMake(startPoint.latitude, startPoint.longitude);
    self.destnationCoordinate = CLLocationCoordinate2DMake(destinationPoint.latitude, destinationPoint.longitude);
    
    self.startAnnotation.coordinate = CLLocationCoordinate2DMake(startPoint.latitude, startPoint.longitude);
    self.destinationAnnotation.coordinate = CLLocationCoordinate2DMake(destinationPoint.latitude, destinationPoint.longitude);
    self.startAnnotation.title = @"起点";
    self.destinationAnnotation.title = @"终点";
    [self.mapView addAnnotation:self.startAnnotation];
    [self.mapView addAnnotation:self.destinationAnnotation];
    
    
    AMapDrivingRouteSearchRequest *navi = [[AMapDrivingRouteSearchRequest alloc] init];
    
    navi.requireExtension = YES;
    navi.strategy = 0;
    
    navi.origin = startPoint;
    if (wayPoints) {
        
        navi.waypoints = wayPoints;
    }
    navi.destination = destinationPoint;
    
    [self.search AMapDrivingRouteSearch:navi];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end




